package com.example.administrator.hospitalmap;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.hospitalmap.entity.HospitalDetail;
import com.squareup.picasso.Picasso;
import com.tangula.android.utils.ToastUtils;
import com.tangula.utils.JsonUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Locale;

public class DetailActivity extends AppCompatActivity {

    private static final int REQ_PERM_CALL_PHONE = 999;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);


        String json = getIntent().getStringExtra("hospital");
        if(StringUtils.isNotBlank(json)){
            HospitalDetail dt = JsonUtils.fromJson(json, HospitalDetail.class);
            displayHosptial(dt);
        }
    }

    private void displayHosptial(final HospitalDetail dt) {

        try {
            new Picasso.Builder(this).build().load(dt.getPic()).into((ImageView) this.findViewById(R.id.vw_detail_icon));
        }catch(Exception e){
            Log.e("console", e.getLocalizedMessage(), e);
        }
        ((TextView)this.findViewById(R.id.vw_detail_name_edit)).setText(dt.getNama());

        ((TextView)this.findViewById(R.id.vw_detail_alamat_edit)).setText(dt.getAlamat());

        ((TextView)this.findViewById(R.id.vw_detail_telepon_edit)).setText(dt.getTelp());

        ((TextView)this.findViewById(R.id.vw_detail_jenis_faskes_edit)).setText(dt.getJFaskes());

        this.findViewById(R.id.vw_detail_petunjuk_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String urlString = String.format(Locale.getDefault(),"http://maps.google.com/maps?daddr=%f,%f",Float.parseFloat(dt.getLat()), Float.parseFloat(dt.getLot()));
                    Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(urlString));
                    if (isPackageExisted("com.google.android.apps.maps")) {
                        intent.setPackage("com.google.android.apps.maps");
                    }
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Log.w("console", e.getLocalizedMessage(), e);
                }
            }
        });

        this.findViewById(R.id.vw_detail_hubungi_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (Build.VERSION.SDK_INT >= 23) {
                    if(ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, REQ_PERM_CALL_PHONE);
                    }
                }

                callHospital(dt);
            }
        });

    }

    private void callHospital(final HospitalDetail dt){
        try{
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + dt.getTelp()));
            startActivity(intent);
            Log.v("console", "send a call:"+dt.getTelp());
        } catch(SecurityException e) {
            Log.w("console", e.getLocalizedMessage(), e);
        }
    }

    public boolean isPackageExisted(String targetPackage) {
        for (ApplicationInfo packageInfo : getPackageManager().getInstalledApplications(0)) {
            if (packageInfo.packageName.equals(targetPackage))
                return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(requestCode==REQ_PERM_CALL_PHONE){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                ToastUtils.showToastLong("Please click the Call button.");
            }else{
                ToastUtils.showToastLong("No permission, can't call the hospital.");
            }
        }
    }


}
